import React from "react";
import { Form, Button, Input, message } from "antd";
import { useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import axios from "axios";

import "./index.scss";

export default function PostsAdd() {
  const navigate = useNavigate();
  const token = useSelector((state) => state.user.token);
  const userId = useSelector((state) => state.user.userId);

  async function onAdd(values) {
    try {
      await axios.post(
        "http://localhost:5000/posts",
        {
          title: values.title,
          body: values.body,
          // 当前登录的用户Id
          userId: userId,
        },
        {
          headers: {
            Authorization: token,
          },
        }
      );
      message.success("新增成功");
      // 后退到列表页面
      navigate(-1);
    } catch (error) {
      message.error(error.message);
    }
  }

  return (
    <div className="posts-add">
      <h1>新增帖子</h1>
      <Form onFinish={onAdd}>
        <Form.Item
          name="title"
          rules={[
            {
              required: true,
              message: "请输入标题",
            },
          ]}
        >
          <Input placeholder="标题" />
        </Form.Item>

        <Form.Item
          name="body"
          rules={[
            {
              required: true,
              message: "请输入正文",
            },
          ]}
        >
          <Input.TextArea rows={4} placeholder="正文" />
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit">
            新增
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}
